var textAreaSelectionObjects = [];

function getTextAreaSelection(id) {
    if (typeof(textAreaSelectionObjects[id]) == "undefined") {
        textAreaSelectionObjects[id] = new textAreaSelectionHelper(id);
    }
    return textAreaSelectionObjects[id];
}

function textAreaSelectionHelper(id) {
    var obj = document.getElementById(id);
    this.target = obj;
    this.target.carretHandler = this;
    this.target.onchange = _textareaSaver;
    this.target.onclick = _textareaSaver;
    this.target.onkeyup = _textareaSaver;
    this.target.onfocus = _textareaSaver;
    if(document.attachEvent) this.target.onselect = _textareaSaver;
    this.start=-1;
    this.end=-1;
    this.scroll=-1;
    this.iesel=null;
}

textAreaSelectionHelper.prototype = {
    getSelectedText : function() {
        return this.iesel? this.iesel.text: (this.start>=0&&this.end>this.start)? this.target.value.substring(this.start,this.end): "";
    },
    setSelectedText : function(text, secondtag) {
        if (this.iesel) {
            if (typeof(secondtag) == "string") {
                var l = this.iesel.text.length;
                this.iesel.text = text + this.iesel.text + secondtag;
                this.iesel.moveEnd("character", -secondtag.length);
                this.iesel.moveStart("character", -l);
            } else {
                this.iesel.text = text;
            }
            this.iesel.select();
        } else if (this.start >= 0 && this.end >= this.start) {
            var left = this.target.value.substring(0, this.start);
            var right = this.target.value.substr(this.end);
            var scont = this.target.value.substring(this.start, this.end);
            if (typeof(secondtag) == "string") {
                this.target.value = left + text + scont + secondtag + right;
                this.end = this.target.selectionEnd=this.start+text.length+scont.length;
                this.start = this.target.selectionStart = this.start + text.length;
            } else {
                this.target.value = left + text + right;
                this.end = this.target.selectionEnd = this.start + text.length;
                this.start = this.target.selectionStart = this.start + text.length;
            }
            this.target.scrollTop = this.scroll;
            this.target.focus();
        } else {
            this.target.value += text + ((typeof(secondtag) == "string") ? secondtag: "");
            if (this.scroll >= 0) this.target.scrollTop = this.scroll;
        }
    },
    setSelectedTextWithClear : function(text) {
        if (this.iesel) {
            if (typeof(secondtag) == "string") {
                var l = this.iesel.text.length;
                this.iesel.text = text;
                this.iesel.moveEnd("character", -secondtag.length);
                this.iesel.moveStart("character", -l);
            } else {
                this.iesel.text = text;
            }
            this.iesel.select();
        } else if (this.start >= 0 && this.end >= this.start) {
            var left = this.target.value.substring(0, this.start);
            var right = this.target.value.substr(this.end);
            var scont = this.target.value.substring(this.start, this.end);
            if (typeof(secondtag) == "string") {
                this.target.value = left + text + right;
                this.end = this.target.selectionEnd=this.start+text.length+scont.length;
                this.start = this.target.selectionStart = this.start + text.length;
            } else {
                this.target.value = left + text + right;
                this.end = this.target.selectionEnd = this.start + text.length;
                this.start = this.target.selectionStart = this.start + text.length;
            }
            this.target.scrollTop = this.scroll;
            this.target.focus();
        } else {
            this.target.value += text + ((typeof(secondtag) == "string") ? secondtag: "");
            if (this.scroll >= 0) this.target.scrollTop = this.scroll;
        }
    },
    getText : function() {
        return this.target.value;
    },
    setText : function(text) {
        this.target.value = text;
    }
}

function _textareaSaver() {
    if(document.selection) {
        this.carretHandler.iesel = document.selection.createRange().duplicate();
    } else if(typeof(this.selectionStart) != "undefined") {
        this.carretHandler.start = this.selectionStart;
        this.carretHandler.end = this.selectionEnd;
        this.carretHandler.scroll = this.scrollTop;
    } else {
        this.carretHandler.start = this.carretHandler.end = -1;
    }
}

function makemarkitup(textarea) {
    var textareaSelector = getTextAreaSelection(textarea);

    $("#bold").click(
        function() {
            textareaSelector.setSelectedText("[b]", "[/b]");
        }
    );

    $("#italic").click(
        function() {
            textareaSelector.setSelectedText("[i]", "[/i]");
        }
    );

    $("#underline").click(
        function() {
            textareaSelector.setSelectedText("[u]", "[/u]");
        }
    );

    $("#link").click(
        function() {
            var url = prompt("Введите ссылку:", "http://");
            if(url != null) {
                textareaSelector.setSelectedText("[url=" + url + "]", "[/url]");
            }
        }
    );
        
    $("#colors").click(
        function() {
            var color = prompt("Введите код цвета:", "#");
            if(color != null) {
                textareaSelector.setSelectedText("[color=" + color + "]", "[/color]");
            }
        }
    );

    $("img").each(
        function() {
            if($(this).parent().parent().parent().parent().attr("id") == "tableColors") {
                $(this).click(
                    function() {
                        textareaSelector.setSelectedText("[color=" + $(this).attr("id") + "]", "[/color]");
                    }
                );
            }
        }
    );

    $("#fonts").click(
        function() {
            var font = prompt("Введите размер шрифта:", "14");
            if(font != null) {
                textareaSelector.setSelectedText("[size=" + font + "]", "[/size]");
            }
        }
    );

    $("img").each(
        function() {
            if($(this).parent().parent().parent().parent().attr("id") == "tableFonts") {
                $(this).click(
                    function() {
                        switch($(this).attr("id")) {
                            case "small":
                                font = "12";
                                break;
                            case "normal":
                                font = "14";
                                break;
                            case "big":
                                font = "16";
                                break;
                            default:
                                font = "14";
                                break;
                        }
                        textareaSelector.setSelectedText("[size=" + font + "]", "[/size]");
                    }
                );
            }
        }
    );

    $("#listBullet").click(
        function() {
            textareaSelector.setSelectedText("[list]\r\n", "\r\n[/list]");
        }
    );

    $("#listNumeric").click(
        function() {
            var startNum = prompt("Введите номер первого элемента списка:", "1");
            if(startNum != null) {
                textareaSelector.setSelectedText("[list=" + startNum + "]\r\n", "\r\n[/list]");
            }
        }
    );

    $("#listItem").click(
        function() {
            textareaSelector.setSelectedText("[*]", "");
        }
    );

    $("#quotes").click(
        function() {
            textareaSelector.setSelectedText("[quote]", "[/quote]");
        }
    );

    $("#code").click(
        function() {
            textareaSelector.setSelectedText("[code]\r\n", "\r\n[/code]");
        }
    );

    $("div.emoticons > img").click(
        function() {
            textareaSelector.setSelectedTextWithClear($(this).attr("alt"));
        }
    );

    $("#clean").click(
        function() {
            var text = $("#" + textarea).val();
            text = text.replace(/\[b\]([\s\S]*)\[\/b\]/ig, "\$1");
            text = text.replace(/\[i\]([\s\S]*)\[\/i\]/ig, "\$1");
            text = text.replace(/\[u\]([\s\S]*)\[\/u\]/ig, "\$1");
            text = text.replace(/\[url=([^\]]*)\]([\s\S]*)\[\/url\]/ig, "\$2");
            text = text.replace(/\[img=([^\]]*)\]([\s\S]*)\[\/img\]/ig, "\$2");
            text = text.replace(/\[color=([^\]]*)\]([\s\S]*)\[\/color\]/ig, "\$2");
            text = text.replace(/\[size=([^\]]*)\]([\s\S]*)\[\/size\]/ig, "\$2");
            text = text.replace(/\[list=([^\]]*)\]([\s\S]*)\[\/list\]/ig, "\$2");
            text = text.replace(/\[list\]([\s\S]*)\[\/list\]/ig, "\$1");
            text = text.replace(/\[\*\]([\s\S]*)\[\*\]/ig, "\$1");
            text = text.replace(/\[quote\]([\s\S]*)\[\/quote\]/ig, "\$1");
            text = text.replace(/\[code\]([\s\S]*)\[\/code\]/ig, "\$1");
            $("#" + textarea).val(text);
        }
    );

    var previewWindow = null;

    $("#preview").click(
        function() {
            if (previewWindow == null) {
                previewWindow = $("<iframe id=\"markitupPreviewFrame\"></iframe>");
                previewWindow.insertAfter("#" + textarea);
                previewWindow = previewWindow[previewWindow.length - 1].contentWindow || frame[previewWindow.length - 1];
            }

            $.ajax(
                {
                    url: "/admin/markitupPreview.php",
                    type: "POST",
                    data: "data=" + $("#" + textarea).val(),
                    success: function(response) {
                        previewWindow.document.open();
                        previewWindow.document.write(response);
                        previewWindow.document.close();
                    }
                }
            );
        }
    );
}